import {
	CONFIG,
	headers1,
	kimiHeaders
} from "../utils/config.js"

uni.addInterceptor("request", {
	invoke(options) {
		// console.log("进入拦截器2");
		if (options.url.startsWith(CONFIG.leanbase)) {
			options.header = headers1;
		}

		if (options.url.startsWith(CONFIG.kimi_url)) {
			options.header = kimiHeaders;
		}

	}
})


let $request = (url, data, method = 'GET') => {
	console.log("send request:" + url);
	//请求之前，显示等待加载图标
	uni.showLoading({
		title: "加载中..."
	})
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			data: data || {},
			method,
			success(res) {
				if (res.statusCode >= 200 && res.statusCode < 300) {
					resolve(res.data)

				} else {
					// 其他错误
					uni.showToast({
						icon: 'none',
						title: '数据获取错误',
					})
					reject(res)
				}

			},
			fail(err) {
				uni.showToast({
					icon: 'none',
					title: '网络错误，请重试。',
				})
				reject(err)

			},
			complete() {
				uni.hideLoading()
			}
		})
	})

}

// 将base_url地址挂载在uni全局对象上
uni.$base_url = CONFIG.leanbase

// 将网络请求函数挂载在全局对象uni上
uni.$request = $request


// 以reqeust为基础,封装最常用的get,post请求函数,挂载在uni对象上
uni.$get = (url, data) => {
	return $request(url, data)
}

uni.$post = (url, data) => {
	return $request(url, data, "POST")
}
uni.$put = (url, data) => {
	return $request(url, data, "PUT")
}

uni.$del = (url, data) => {
	return $request(url, data, "DELETE")
}